import * as vscode from 'vscode';

export class ApiCodeDecorator {
    private errorDecorationType: vscode.TextEditorDecorationType;
    private warningDecorationType: vscode.TextEditorDecorationType;
    private activeEditor: vscode.TextEditor | undefined;
    private disposables: vscode.Disposable[] = [];
    private debounceTimer: NodeJS.Timeout | undefined;

    constructor() {
        // 初始化装饰器样式
        this.errorDecorationType = vscode.window.createTextEditorDecorationType({
            textDecoration: 'underline wavy red',
            overviewRulerColor: 'red',
            overviewRulerLane: vscode.OverviewRulerLane.Right
        });

        this.warningDecorationType = vscode.window.createTextEditorDecorationType({
            textDecoration: 'underline wavy yellow',
            overviewRulerColor: 'yellow',
            overviewRulerLane: vscode.OverviewRulerLane.Right
        });

        // 初始化事件监听
        this.initializeEventListeners();
        this.activeEditor = vscode.window.activeTextEditor;
    }

    private initializeEventListeners(): void {
        // 编辑器切换事件
        this.disposables.push(vscode.window.onDidChangeActiveTextEditor(editor => {
            this.activeEditor = editor;
        }));

        // 文档内容变化事件
        this.disposables.push(vscode.workspace.onDidChangeTextDocument(event => {
            if (this.activeEditor && event.document === this.activeEditor.document) {
                // debouncedUpdate();
            }
        }));
    }

    private debounce(func: () => void, delay: number): void {
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }
        this.debounceTimer = setTimeout(func, delay);
    }

    public decorateLine(line: number, startCol: number, endCol: number): void {
        if (!this.activeEditor) {
            return;
        }

        const document = this.activeEditor.document;
        const totalLines = document.lineCount;

        if (line < 0 || line >= totalLines) {
            vscode.window.showErrorMessage(`行号 ${line + 1} 无效，请输入 1 到 ${totalLines} 之间的行号。`);
            return;
        }

        const range = new vscode.Range(
            new vscode.Position(line, startCol),
            new vscode.Position(line, endCol)
        );

        this.activeEditor.setDecorations(this.errorDecorationType, [range]);
    }
    public clearAllDecorations(): void {
        if (!this.activeEditor) {
            return;
        }

        // Clear all decorations by setting empty ranges
        this.activeEditor.setDecorations(this.errorDecorationType, []);
        this.activeEditor.setDecorations(this.warningDecorationType, []);
    }
    public dispose(): void {
        // 清理所有资源
        this.errorDecorationType.dispose();
        this.warningDecorationType.dispose();
        this.disposables.forEach(d => d.dispose());
    }
}

export function deactivate() {}